package com.pug.test.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.pug.test.dto.BuyReqDTO;
import com.pug.test.dto.BuyRespDTO;
import com.pug.test.service.IBusinessService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xq.pug.common.exception.ServiceException;
import xq.pug.common.result.R;
import xq.pug.feign.dto.order.OrderMakeFeignReqDTO;
import xq.pug.feign.dto.order.OrderMakeFeignRespDTO;
import xq.pug.feign.dto.product.DedInventoryFeignReqDTO;
import xq.pug.feign.service.order.OrderServiceFeign;
import xq.pug.feign.service.product.InventoryServiceFeign;

/**
 * @program: xq_pug_alibabacloud_parent
 * @description:
 * @author: Mr.Ren
 * @create: 2023-07-12 21:52
 **/
@Service
@Slf4j
public class BusinessService implements IBusinessService {

    @Autowired
    private OrderServiceFeign orderServiceFeign;
    @Autowired
    private InventoryServiceFeign inventoryServiceFeign;

    @Override
    @GlobalTransactional
    public BuyRespDTO buy(BuyReqDTO dto) {
        //扣减库库存--事务A获取全局事务锁（global-lock）
        DedInventoryFeignReqDTO dedInventoryFeignReqDTO = new DedInventoryFeignReqDTO();
        dedInventoryFeignReqDTO.setProductCode(dto.getProductCode());
        dedInventoryFeignReqDTO.setDedCount(dto.getNum());
        R<Integer> inventoryResult = inventoryServiceFeign.dedInventory(dedInventoryFeignReqDTO);
        if (inventoryResult.isFail()){
            log.error("扣减库存失败");
            throw new ServiceException(inventoryResult.getMessage());
        }
        log.info("扣减库存成功");
        //事务A释放全局事务锁（global-lock）

        //下单 事务B获取全局事务锁（global-lock）
        OrderMakeFeignReqDTO orderMakeFeignReqDTO = BeanUtil.copyProperties(dto, OrderMakeFeignReqDTO.class);
        R<OrderMakeFeignRespDTO> orderResult = orderServiceFeign.orderMake(orderMakeFeignReqDTO);
        if (orderResult.isFail()){
            log.error("下单失败");
            throw new ServiceException(orderResult.getMessage());
        }
        log.info("下单并扣款成功");
        int error = 1/0;

        //返回成功信息
        BuyRespDTO buyRespDTO = new BuyRespDTO();
        buyRespDTO.setUserCode(dto.getUserCode());
        buyRespDTO.setProductCode(dto.getProductCode());
        return buyRespDTO;
    }
}
